建完表格後來寫api,來寫一個訂閱的api,weatherSubscribe(),只允許post 方法。
main/views.py ,傳入有選取的行政區,還有email,這邊用update_or_create,會先去找有沒有這個email,沒有就建立,有得話就修改選取行政區。
這樣同個email,重新按下訂閱一次就會更新。
def weatherSubscribe(request):
if request.method == "POST":
locationNameList = request.POST.getlist("locationNameList[]", [])
email = request.POST.get("email")
if not locationNameList or not email:
return JsonResponse({"msg": "no create"})
weatherSubscribe, isCreate = WeatherSubscribe.objects.update_or_create(
email=email,
defaults={
"districts": locationNameList
})
return JsonResponse({"msg": "success"})
main/urls.py
...
path('api/weatherSubscribe/', views.weatherSubscribe),
...
前端,加上訂閱按鈕,寫一個送reqFunc,headers 要加上csrf_token,
main/main.html
{% csrf_token %}
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">Email</span>
</div>
<input id="emailInput"
type="email" class="form-control" placeholder="xxx@gmail.com">
</div>
...
<button id="weatherSubscribeBtn" class="btn btn-warning" type="button">
訂閱
</button>
...
const reqWeatherSubscribe = (selectedDistrictChxArr, email) => {
// 加上csrf_token
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value
$.ajax({
url: `/api/weatherSubscribe/`,
headers: {'X-CSRFToken': csrftoken},
type: "post",
data: {
locationNameList: selectedDistrictChxArr,
email: email
}
,
success: (res) => {
}
})
}
$(document).on("click", "#weatherSubscribeBtn", (e) => {
e.preventDefault();
let selectedDistrictChxArr = []
$('.districtChx[name=checkboxDistrict]:checked').each(function (i) {
selectedDistrictChxArr.push(this.value)
})
const email = $('#emailInput').val()
reqWeatherSubscribe(selectedDistrictChxArr, email)
})
結果圖:
按下訂閱後
可以去後台admin看,http://localhost:8000/admin/
就有剛剛新增的那筆紀錄了
也訂閱也有取消訂閱,也把這寫一寫,
weatherUnsubscribe ,只傳email,就去資料庫查,就直接刪除那筆資料,這邊就沒有寫如果查不到這些驗證了。
def weatherUnsubscribe(request):
if request.method == "POST":
email = request.POST.get("email")
if not email:
return JsonResponse({"msg": "no create"})
WeatherSubscribe.objects.filter(email=email).delete()
return JsonResponse({"msg": "success"})
main/urls.py
...
path('api/weatherUnsubscribe/', views.weatherUnsubscribe),
...
前端加一個按鈕,取消訂閱,這裡只要email就好。
...
<button id="weatherUnsubscribeBtn" class="btn btn-danger" type="button">
取消訂閱
</button>
...
const reqWeatherUnsubscribe = (email) => {
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value
$.ajax({
url: `/api/weatherUnsubscribe/`,
headers: {'X-CSRFToken': csrftoken},
type: "post",
data: {email: email},
success: (res) => {
}
})
}
$(document).on("click", "#weatherUnsubscribeBtn", (e) => {
e.preventDefault();
const email = $('#emailInput').val()
reqWeatherUnsubscribe(email)
})
結果畫面
執行完,就會看到那筆資料被刪掉了
參考資料: